<template>
	<view class="container">
		<view  class="title">简单加法计算器</view>
		
		<view class="input-group">
			<input type="number" v-model.number="num1" placeholder="请输入第一个数字"/>
			<input type="number" v-model.number="num2" placeholder="请输入第二个数字"/>
		</view>
		
		<button class="calc-btn" @click="calculate">计算</button>
		
		<view class="result" v-if="result !== null">
			计算结果: {{ result }}
		</view>
		
		<view class="error" v-if="errorMsg">{{ errorMsg }}</view>
		
		<!- 添加历史记录按钮 -->
		<button class="history-btn" @click="goToHistory"></button>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				num1: 0,
				num2: 0,
				result: null,
				errorMsg: ''
			}
		},
		methods: {
			async calculate() {
				this.result = null;
				this.errorMsg = '';
				
				if (!this.num1 || !this.num2) {
					this.errorMsg = '请输入有效的数字';
					return;
				}
				
				try {
					const res = await uniCloud.callFunction({
						name: 'add',
						data: {
							num1: parseFloat(this.num1),
							num2: parseFloat(this.num2)
						}
					});
					
					if (res.result.code === 200) {
						this.result = res.result.data;
						
						//保存计算记录
						await uniCloud.callFunction({
							name: 'saveRecord',
							data:  {
								num1: parseFloat(this.num1),
								num2: parseFloat(this.num2),
								result: this.result
							}
						})
					} else {
						this.errorMsg = res.result.message || '计算失败';
					}
				} catch (e) {
					this.errorMsg = '调用云函数失败：' + e.message;
					console.error('云函数调用出错：', e);
				}
			},
			
			goToHistory() {
				uni.navigateTo({
					url: 'pages/history/index'
				})
			}
		}
	}
</script>

<style>
.container {
    padding: 20px;
}

.title {
    font-size: 20px;
    text-align: center;
    margin-bottom: 20px;
}

.input-group {
    margin-bottom: 20px;
}

.input-group input {
    border: 1px solid #ddd;
    border-radius: 4px;
    padding: 10px;
    margin-bottom: 10px;
}

.calc-btn {
    background-color: #007AFF;
    color: white;
    padding: 10px;
    border-radius: 4px;
    text-align: center;
}

.result {
    margin-top: 20px;
    padding: 10px;
    background-color: #f0f0f0;
    border-radius: 4px;
    text-align: center;
}

.error {
    margin-top: 10px;
    color: red;
    text-align: center;
}
</style>
